package com.hckj.jianzhijia.fragments;

import android.app.Application;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.radar.RadarNearbyResult;
import com.baidu.mapapi.radar.RadarNearbySearchOption;
import com.baidu.mapapi.radar.RadarSearchError;
import com.baidu.mapapi.radar.RadarSearchListener;
import com.baidu.mapapi.radar.RadarSearchManager;
import com.baidu.mapapi.radar.RadarUploadInfo;
import com.hckj.jianzhijia.JianzhijiaApplacation;
import com.hckj.jianzhijia.R;
import com.hckj.jianzhijia.popupwindows.UserMapPopWin;
import com.hckj.jianzhijia.utils.ToastUtils;

import static android.content.Context.SENSOR_SERVICE;


public class MainPushFragment extends Fragment implements UserMapPopWin.PopWinInterface ,SensorEventListener, RadarSearchListener, BaiduMap.OnMarkerClickListener, BaiduMap.OnMapClickListener {

    private TextView tv_apply_push;

    // 地图相关
    private MapView mMapView;
    private BaiduMap mBaiduMap;
    BitmapDescriptor ff3 = BitmapDescriptorFactory.fromResource(R.drawable.icon_marka);
    // 周边雷达相关
    private String userID;
    private String userComment;
    private boolean uploadAuto = false;
    // 定位相关
    LocationClient mLocClient;
    public MyLocationListener myListener = new MyLocationListener();
    private MyLocationConfiguration.LocationMode mCurrentMode;
    private SensorManager mSensorManager;
    BitmapDescriptor mCurrentMarker;
    private LatLng pt = null;
    private Double lastX = 0.0;
    private int mCurrentDirection = 0;
    private double mCurrentLat = 0.0;
    private double mCurrentLon = 0.0;
    private float mCurrentAccracy;
    private int pageIndex = 0;
    // UI相关
    Button requestLocButton;
    boolean isFirstLoc = true; // 是否首次定位
    private MyLocationData locData;
    // TAG
    private static final String TAG = "MainPushFragment";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        JianzhijiaApplacation mApplication = ((JianzhijiaApplacation) getActivity().getApplication());
        userID = mApplication.getCompanyUser().getObjectId();
        Log.d(TAG, "onCreated: "+userID.toString());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.layout_push_fragment, container, false);

        tv_apply_push = (TextView) view.findViewById(R.id.tv_apply_push);
        tv_apply_push.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 重启定位
                if (mLocClient != null) {
                    mLocClient.stop();
                }
                initLocation();
                ToastUtils.showToast(getActivity(),"刷新完成");
            }
        });
        initMap(view);
        initLocation();
        initRadar();
        return view;
    }

    private void initMap(View view) {
        // btn initialize
        requestLocButton = (Button) view.findViewById(R.id.button1);
        mSensorManager = (SensorManager) getActivity().getApplicationContext().getSystemService(SENSOR_SERVICE);//获取传感器管理服务
        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
        requestLocButton.setText("普通");
        View.OnClickListener btnClickListener = new View.OnClickListener() {
            public void onClick(View v) {
                switch (mCurrentMode) {
                    case NORMAL:
                        requestLocButton.setText("跟随");
                        mCurrentMode = MyLocationConfiguration.LocationMode.FOLLOWING;
                        mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
                                mCurrentMode, true, mCurrentMarker));
                        MapStatus.Builder builder = new MapStatus.Builder();
                        builder.overlook(0);
                        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                        break;
                    case FOLLOWING:
                        requestLocButton.setText("罗盘");
                        mCurrentMode = MyLocationConfiguration.LocationMode.COMPASS;
                        mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
                                mCurrentMode, true, mCurrentMarker));
                        break;
                    case COMPASS:
                        requestLocButton.setText("普通");
                        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
                        mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
                                mCurrentMode, true, mCurrentMarker));
                        MapStatus.Builder builder1 = new MapStatus.Builder();
                        builder1.overlook(0);
                        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder1.build()));
                        break;
                    default:
                        break;
                }
            }
        };
        requestLocButton.setOnClickListener(btnClickListener);
        // map initialize
        mMapView = (MapView) view.findViewById(R.id.map);
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setOnMarkerClickListener(this);
        mBaiduMap.setOnMapClickListener(this);
        mBaiduMap.setMyLocationEnabled(true);
        // 开启室内图
        mBaiduMap.setIndoorEnable(true);
    }

    private void initLocation() {
        // 定位初始化
        mLocClient = new LocationClient(getActivity());
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(5000);
        mLocClient.setLocOption(option);
        mLocClient.start();
    }

    private void initRadar() {
        // 周边雷达设置监听
        RadarSearchManager.getInstance().addNearbyInfoListener(this);
        // 周边雷达设置用户，id为空默认是设备标识
        RadarSearchManager.getInstance().setUserID(userID);
        Log.d(TAG, "initRadar: "+userID);
    }

    // 方向监听
    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        double x = sensorEvent.values[SensorManager.DATA_X];
        if (Math.abs(x - lastX) > 1.0) {
            mCurrentDirection = (int) x;
            locData = new MyLocationData.Builder()
                    .accuracy(mCurrentAccracy)
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mCurrentDirection).latitude(mCurrentLat)
                    .longitude(mCurrentLon).build();
            mBaiduMap.setMyLocationData(locData);
        }
        lastX = x;
    }
    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

    @Override
    public void junpToInfoActivity(int position) {

    }

    // 定位SDK回调
    /**
     * 定位SDK监听函数
     */
    public class MyLocationListener extends BDAbstractLocationListener {
        private static final String TAG = "MyLocationListener";
        private String lastFloor = null;
        @Override
        public void onReceiveLocation(BDLocation arg0) {
            // TODO Auto-generated method stub
            if (arg0 == null || mBaiduMap == null) {
                return;
            }
            // ToastUtils.showToast(getActivity(), "获取定位成功");
            Log.d(TAG, "onReceiveLocation: success");
            pt = new LatLng(arg0.getLatitude(), arg0.getLongitude());
            mCurrentLat = arg0.getLatitude();
            mCurrentLon = arg0.getLongitude();
            mCurrentAccracy = arg0.getRadius();
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(arg0.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(arg0.getLatitude())
                    .longitude(arg0.getLongitude()).build();
            if (mBaiduMap != null) {
                mBaiduMap.setMyLocationData(locData);
            }
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(arg0.getLatitude(),
                        arg0.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(18.0f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            }
            // 上传位置
            RadarUploadInfo info = new RadarUploadInfo();
            info.comments = userComment;
            info.pt = pt;
            RadarSearchManager.getInstance().uploadInfoRequest(info);
            // 查询周边
            RadarNearbySearchOption option = new RadarNearbySearchOption()
                    .centerPt(pt).pageNum(pageIndex).radius(2000).pageCapacity(11);
            RadarSearchManager.getInstance().nearbyInfoRequest(option);
        }
    }


    // 上传位置回调
    @Override
    public void onGetUploadState(RadarSearchError error) {
        // TODO Auto-generated method stub
        if (error == RadarSearchError.RADAR_NO_ERROR) {
            // 上传成功
            if (!uploadAuto) {
                // ToastUtils.showToast(getActivity(), "单次上传位置成功");
            }
        } else {
            // 上传失败
            if (!uploadAuto) {
                // ToastUtils.showToast(getActivity(), "单次上传位置失败");
            }
        }
    }

    // 查询周边回调
    @Override
    public void onGetNearbyInfoList(RadarNearbyResult result,
                                    RadarSearchError error) {
        // TODO Auto-generated method stub
        if (error == RadarSearchError.RADAR_NO_ERROR) {
            // ToastUtils.showToast(getActivity(), "查询周边成功");
            // 处理数据
            parseResultToMap(result);
        } else {
            // 获取失败
            // ToastUtils.showToast(getActivity(), "查询周边失败");
            Log.d(TAG, "onGetNearbyInfoList: "+error.toString());
        }
    }

    // 清除信息回调
    @Override
    public void onGetClearInfoState(RadarSearchError error) {
        // TODO Auto-generated method stub
        if (error == RadarSearchError.RADAR_NO_ERROR) {
            // 清除成功
            ToastUtils.showToast(getActivity(), "清除位置成功");
        } else {
            // 清除失败
            ToastUtils.showToast(getActivity(), "清除位置失败");
        }
    }

    /**
     * 更新结果地图
     *
     * @param res
     */
    public void parseResultToMap(RadarNearbyResult res) {
        mBaiduMap.clear();
        if (res != null && res.infoList != null && res.infoList.size() > 0) {
            for (int i = 0; i < res.infoList.size(); i++) {
                MarkerOptions option = new MarkerOptions().icon(ff3).position(res.infoList.get(i).pt);
                Bundle des = new Bundle();
                if (res.infoList.get(i).comments == null || res.infoList.get(i).comments.equals("")) {
                    des.putString("comments", "没有备注");
                } else {
                    des.putString("comments", res.infoList.get(i).comments);
                }
                if (res.infoList.get(i).userID == null || res.infoList.get(i).userID.equals("")) {
                    des.putString("userID", "没有昵称");
                } else {
                    des.putString("userID", res.infoList.get(i).userID);
                }

                option.extraInfo(des);
                mBaiduMap.addOverlay(option);
            }
        }
    }

    @Override
    public void onMapClick(LatLng point) {
        // TODO Auto-generated method stub
        mBaiduMap.hideInfoWindow();
    }

    @Override
    public boolean onMapPoiClick(MapPoi poi) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        // TODO Auto-generated method stub
        mBaiduMap.hideInfoWindow();
        if (marker != null) {
            ToastUtils.showToast(getActivity(), marker.getExtraInfo().getString("userID"));
            // 对点击事件进行处理
            // addFriend(String userID);
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
        //为系统的方向传感器注册监听器
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                SensorManager.SENSOR_DELAY_UI);
    }

    @Override
    public void onStop() {
        mSensorManager.unregisterListener(this);
        super.onStop();
    }

    @Override
    public void onDestroy() {
        // 退出时销毁定位
        mLocClient.stop();
        // 释放周边雷达相关
        RadarSearchManager.getInstance().removeNearbyInfoListener(this);
        RadarSearchManager.getInstance().clearUserInfo();
        RadarSearchManager.getInstance().destroy();
        // 释放地图
        ff3.recycle();
        mMapView.onDestroy();
        mBaiduMap = null;
        super.onDestroy();
    }

    /*
    other functions
     */

    public static MainPushFragment newInstance() {
        MainPushFragment fragment = new MainPushFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    public MainPushFragment() {


    }


}
